var BIG_SUMM_1_ID = 4;
var BIG_SUMM_2_ID = 6;
var BIG_SUMM_3_ID = 7;
var BIG_SUMM_1_LIMIT = 10000;
var BIG_SUMM_2_LIMIT = 30000;
var BIG_SUMM_3_LIMIT = 50000;
var LIMIT_IN = 100000;
var MIN_IN = 0;
var MIN_IN_CURR_NAME = 'USD';
var MIN_OUT = 0;
var MIN_OUT_CURR_NAME = 'USD';
var currency_multy = 1;
var name_mavro = '';
var selected_currency_id = 840;
var start_rest = 0;
var prev_summ = 0;
var today_summ = 0;
var rate_to_usd = 1;
var to_dist = 0;
var id_country = 0;
var data_out_max = 0;
var total_out = 0;
function calcSums($itm) {
    var $rest = $itm.find('._rest');
    var $total = $itm.find('._total');
    var s = start_rest;
    $itm.find('._mavro_item').each(function() {
        s += parseFloat($(this).val());
    });
    var total = Math.floor(s / currency_multy) * currency_multy;
    $total.val(number_format(total, 0, '.', ' '));
    $rest.val(number_format(s - total, 6, '.', ''));
}
function bindMuEvents($itm) {
    var $rest = $itm.find('._rest');
    var $total = $itm.find('._total');
    data_out_max = parseFloat($itm.find('._out_max_sum').val());
    start_rest = parseFloat($rest.val());
    if (parseFloat($rest.val()) > currency_multy) {
        var total = Math.floor(start_rest / currency_multy) * currency_multy;
        $total.val(number_format(total, 6, '.', ' '));
        $rest.val(number_format(start_rest - total, 6, '.', ' '));
    } else {
        $rest.val(number_format(start_rest, 6, '.', ' '));
    }
    $itm.find('._mavro_item').each(function() {
        var max = parseFloat($(this).attr('data-max'));
        if (max < 0) {
            $(this).val(max);
            $(this).attr("disabled", "disabled");
        }
        calcSums($itm);
    });
    $itm.find('._mavro_item').keyup(function(e) {
        $(this).val(parseFloat($(this).val()));
        if ($(this).val() == 'NaN') {
            $(this).val('0');
        }
        var max = parseFloat($(this).attr('data-max'));
        if (parseFloat($(this).val()) > max) {
            $(this).val(max);
        }
        if (parseFloat($(this).val()) < 0) {
            $(this).val(0);
        }
        var s = 0;
        $itm.find('._mavro_item').each(function() {
            s += parseFloat($(this).val());
        });
        total_out = s;
        if (total_out > data_out_max) {
            var to_i = parseFloat($(this).val()) - (total_out - data_out_max);
            to_i = to_i > 0 ? to_i: 0;
            $(this).val(to_i);
        }
        calcSums($itm);
    });
}
function getAllocation(sum, currentDist) {
    var current = currentDist.concat();
    var point1 = BIG_SUMM_1_LIMIT;
    var point2 = BIG_SUMM_2_LIMIT;
    var point3 = BIG_SUMM_3_LIMIT;
    if (current[0] < point1 && sum > 0) {
        max = (point1 - current[0]);
        if (sum <= max) {
            current[0] += sum;
            sum = 0;
        } else {
            current[0] = point1;
            sum -= max;
        }
    }
    if (current[1] < point2 && sum > 0) {
        max = (point2 - current[1]);
        if (sum <= max) {
            current[1] += sum;
            sum = 0;
        } else {
            current[1] = point2;
            sum -= max;
        }
    }
    if (current[2] < point3 && sum > 0) {
        max = (point3 - current[2]);
        if (sum <= max) {
            current[2] += sum;
            sum = 0;
        } else {
            current[2] = point3;
            sum -= max;
        }
    }
    if (sum > 0) {
        current[3] += sum;
    }
    return current;
}
function roundAuto(total, k, multy) {
    return Math.ceil(total * k / multy) * multy;
}
function getAutoKoef(id_accrule) {
    var k = 1;
    switch (id_accrule) {
    case 59:
        k = 1 / 20;
        break;
    case 58:
        k = 1 / 10;
        break;
    case 57:
        k = 15 / 100;
        break;
    case 56:
        k = 1 / 4;
        break;
    case 55:
        k = 1 / 2;
        break;
    case 54:
        k = 65 / 100;
        break;
    case 63:
        k = 1 / 4;
        break;
    case 62:
        k = 1 / 3;
        break;
    case 61:
        k = 1 / 2;
        break;
    }
    return k;
}
function bindEvents(itm, type_input, $val) {
    var p = itm.parent();
    itm.data('real_value', 0);
    if (type_input) {
        p.find('.div_prev_summ').hide();
    }
    p.find('.translate').each(function() {
        $(this).html(getTranslation($(this).html()));
    });
    p.find('._mavro_item').attr('disabled', 'disabled');
    if (type_input == 1 || type_input == 2) {
        p.find('._mavro_item').hide();
    }
    prev_summ = parseFloat($('#prev_summ_in_curr').val());
    rate_to_usd = parseFloat($('#rate_to_usd').val());
    id_country = goodParseInt($('#id_country').val());
    $('#sum_fix').html(getTranslation($('#sum_fix').html()));
    function sum_fix() {
        today_summ = parseFloat(itm.val());
        if (today_summ < currency_multy) {
            return false;
        }
        if ((type_input == 1 || type_input == 2) && today_summ * rate_to_usd < 2000) {
            showAlert('you_order_can_not_be_less_2000USD');
            return false;
        }
        if (type_input == 0 && today_summ * rate_to_usd > LIMIT_IN) {
            showAlert(getTranslation('you_order_can_not_be_more_{0}USD', LIMIT_IN));
            return false;
        }
        if (type_input == 0 && today_summ < MIN_IN) {
            showAlert(getTranslation('you_order_can_not_be_less_{0}_{1}', MIN_IN, MIN_IN_CURR_NAME));
            return false;
        }
        $(this).hide();
        itm.attr('disabled', 'disabled');
        if (type_input == 0) {
            p.find('._mavro_item').removeAttr('disabled');
        } else {
            p.find('._mavro_checkbox input[type="radio"]').each(function() {
                var id = goodParseInt($(this).val());
                var value = roundAuto(today_summ, getAutoKoef(id), currency_multy);
                $('input._mavro_item[name*="\[' + id + '\]"]').after('<strong>' + value + ' ' + selected_currency.substr(0, 3) + '</strong>');
            });
            p.find('._mavro_checkbox').show().find('input[type="radio"]').click(function() {
                var id = goodParseInt($(this).val());
                var value = roundAuto(today_summ, getAutoKoef(id), currency_multy);
                p.find('._mavro_item').val('0');
                $('input._mavro_item[name*="\[' + id + '\]"]').val(value);
                itm.data('real_value', value);
            });
        }
        if (type_input == 0) {
            today_summ = today_summ * rate_to_usd;
            prev_summ = prev_summ * rate_to_usd;
            var old_dist = getAllocation(prev_summ, new Array(0, 0, 0, 0));
            var new_dist = getAllocation(today_summ, old_dist);
            to_dist = new_dist[0] - old_dist[0];
            var to_20 = new_dist[1] - old_dist[1];
            var to_15 = new_dist[2] - old_dist[2];
            var to_10 = new_dist[3] - old_dist[3];
            if (to_20) {
                to_20 = to_20 / rate_to_usd;
                $('[data-id_rule="' + BIG_SUMM_1_ID + '"]').slideDown().find('._mavro_item').val(number_format(to_20, 0, '.', '')).attr('disabled', 'disabled').removeClass('_mavro_item');
            }
            if (to_15) {
                to_15 = to_15 / rate_to_usd;
                $('[data-id_rule="' + BIG_SUMM_2_ID + '"]').slideDown().find('._mavro_item').val(number_format(to_15, 0, '.', '')).attr('disabled', 'disabled').removeClass('_mavro_item');
            }
            if (to_10) {
                to_10 = to_10 / rate_to_usd;
                $('[data-id_rule="' + BIG_SUMM_3_ID + '"]').slideDown().find('._mavro_item').val(number_format(to_10, 0, '.', '')).attr('disabled', 'disabled').removeClass('_mavro_item');
            }
            to_dist = Math.round(to_dist / rate_to_usd);
        } else {
            to_dist = today_summ;
        }
        p.find('._ototal').html(getTranslation('To distortion: {cnt}', {
            cnt: number_format(to_dist, 0, '.', '')
        }));
    }
    if (goodParseInt($val) > 0) {
        sum_fix.call($('#sum_fix')[0]);
    }
    $('#sum_fix').click(sum_fix).linkbutton({
        iconCls: 'icon-ok'
    });
    p.find('._mavro_item').blur(function() {
        var name = $(this).attr('name');
        var root = this;
        var sumo = 0;
        var total = to_dist;
        p.find('._mavro_item').each(function() {
            if ($(this).attr('name') != name && (type_input == 1 || type_input == 2) && parseFloat($(root).val()) > 0) {
                $(this).val('0');
            }
            if ($(this).attr('name') != name) sumo += parseFloat($(this).val());
        });
        var mul = parseInt($(this).attr('data-multi'), 10);
        var ev = parseFloat($(this).val());
        if (mul) {
            $(this).val(Math.floor(parseFloat($(this).val()) / mul) * mul);
        } else {
            $(this).val(parseFloat($(this).val()));
        }
        if (type_input == 1 || type_input == 2) {
            if (parseFloat($(this).val()) / rate_to_usd > parseFloat($(this).attr('data-max'))) {
                $(this).val(Math.round(parseFloat($(this).attr('data-max')) / rate_to_usd));
            }
        }
        if ($(this).val() == 'NaN') {
            $(this).val('0');
        }
        if (parseFloat($(this).val()) < 0) {
            $(this).val('0');
        }
        var t = parseFloat($(this).val());
        if (sumo + t > total) {
            $(this).val(total - sumo);
            if (mul) {
                $(this).val(Math.floor((total - sumo) / mul) * mul);
            }
        }
        var tt = total - (sumo + parseFloat($(this).val()));
        p.find('._ototal').html(getTranslation('To distortion: {cnt}', {
            cnt: number_format(tt, 0, '.', '')
        }));
    });
    itm.blur(function() {
        var sumo = 0;
        p.find('._mavro_item').each(function() {
            sumo += parseFloat($(this).val());
        });
        $(this).val(parseFloat($(this).val()));
        if ($(this).val() == 'NaN') {
            $(this).val('0');
        }
        if (parseFloat($(this).val()) < 0) {
            $(this).val('0');
        }
        if (parseFloat($(this).val()) < sumo) {
            $(this).val(sumo);
        }
        $(this).val(Math.floor(parseFloat($(this).val()) / currency_multy) * currency_multy);
        var tt = parseFloat($(this).val()) - sumo;
    });
}
function fieldDefault(row) {
    templ = $('#_pattern_field_default').val();
    var field = row;
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        $('#' + field.id).val(field.value);
        if (row.regexp) {
            var rulename = 'v_' + field.id;
            var rule = {};
            rule[rulename] = {
                validator: function(value, param) {
                    if (row.regexp_keys) var exp = new RegExp(row.regexp, row.regexp_keys);
                    else var exp = new RegExp(row.regexp);
                    return exp.test(value);
                },
                message: getTranslation('Field filled invalid!')
            }
            $.extend($.fn.validatebox.defaults.rules, rule);
            $('#' + field.id).validatebox({
                validType: rulename,
                required: field.required
            });
        } else {
            $('#' + field.id).validatebox({
                required: row.required
            });
        }
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldLabel(row) {
    templ = $('#_pattern_field_label').val();
    var field = row;
    return format(templ, field);
}
function fieldDate(row) {
    templ = $('#_pattern_field_date').val();
    var field = row;
    var dt = new Date();
    if (field.value) {
        var p = field.value.split('-');
        dt = new Date(goodParseInt(p[0]), goodParseInt(p[1]) - 1, goodParseInt(p[2]));
    }
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        $('#' + field.id).datebox({
            'required': row.required,
            'value': rusDate(dt),
            'parser': function(d) {
                var p = d.split('.');
                return new Date(p[2], p[1] - 1, p[0]);
            },
            'formatter': rusDate
        });
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldFile(row) {
    templ = $('#_pattern_field_file').val();
    var field = row;
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        if (row.required) {
            $('#' + field.id).attr('required', 'required');
            $('#' + field.id).parent().attr('required', 'required');
        }
        createUploader($('#' + field.id).get(0));
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldInfo(row) {
    templ = $('#_pattern_field_info').val();
    var field = row;
    return format(templ, $.extend(field, field.options));
}
function fieldRequisite(row) {
    templ = $('#_pattern_field_default').val();
    var field = row;
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        $('#' + field.id).requisite(row.options);
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldCombo(row) {
    templ = $('#_pattern_field_combo').val();
    var field = row;
    var opts = row.options ? row.options: [];
    for (var i in opts) {
        opts[i].value = getTranslation(opts[i].value);
    }
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        var valinlist = false;
        for (var i in opts) {
            if (opts[i].id == row.value) {
                valinlist = true;
            }
        }
        $('#' + field.id).combobox({
            'required': row.required,
            'multiple': false,
            'editable': false,
            'value': opts.length ? (valinlist ? row.value: opts[0].id) : '',
            'valueField': 'id',
            'textField': 'value',
            'data': opts
        });
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldMultiCombo(row) {
    templ = $('#_pattern_field_multi_combo').val();
    var field = row;
    var opts = row.options ? row.options: [];
    for (var i in opts) {
        opts[i].value = getTranslation(opts[i].value);
    }
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        $('#' + field.id).combobox({
            'required': row.required,
            'multiple': true,
            'editable': false,
            'valueField': 'id',
            'textField': 'value',
            'data': opts
        });
        var pices = [0];
        if (row.value) {
            pices = row.value.split(',');
            if (pices.length > 1) {
                pices.pop();
                pices.shift();
            }
        }
        $('#' + field.id).combobox('setValues', pices);
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldCaptcha(row) {
    templ = $('#_pattern_field_captcha').val();
    var field = row;
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        var _this = this;
        $('a.translate', this).click(function() {
            $('img', _this).attr('src', '/c?' + (100000 * Math.random() + 10000));
            return false;
        }).text(getTranslation($('a.translate', this).text()));
    };
    field.link = '/c?' + (100000 * Math.random() + 10000);
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldRadio(row) {
    templ = $('#_pattern_field_radio').val();
    templ_i = $('#_pattern_field_radio_item').val();
    var field = row;
    var opts = row.options ? row.options: [];
    var inputs = '';
    var old_pop = -1;
    for (var i in opts) {
        if (typeof(opts[i].pop) != 'undefined') {
            if (old_pop != -1 && old_pop != parseInt(opts[i].pop, 10)) {
                inputs += '<hr style="width: 90%;" />';
            }
            old_pop = parseInt(opts[i].pop, 10);
        }
        inputs += format(templ_i, field.name, field.id + '_' + i, opts[i].id, getTranslation(opts[i].value), field.value == opts[i].id ? ' checked="checked"': '');
    }
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        if (field.required) {
            $('#' + field.id).attr('required', 'required');
        }
    };
    $(this).data('callback', backs);
    return format(templ, field.id, inputs, field.style);
}
function fieldMavroAmounts(row) {
    templ = $('#_pattern_field_mavro_sums').val();
    templ_i = $('#_pattern_field_mavro_sums_item').val();
    var field = row;
    var opts = row.options ? row.options: [];
    if (row.type_input == 1 || row.type_input == 2) {
        opts = row.options_avto;
    }
    var tm = row.curr_mavro ? row.curr_mavro: [];
    var inputs = '';
    for (var i in opts) {
        var multi = opts[i].multiple || 0;
        var valuta_inputs = '<input name="' + field.name + '[mavros][' + opts[i].id + '][currency]" class="_mavro_checkboxes" style="width: 90px;"/>';
        var dop = (row.type_input == 1 || row.type_input == 2) ? (' data-max="' + opts[i].summ_in_max) + '"': '';
        var input = format(templ_i, field.name, opts[i].id, getTranslation(opts[i].value), valuta_inputs, '', dop, multi);
        inputs += input;
    }
    if (!row.type_input) {
        LIMIT_IN = row.limit_in;
        MIN_IN = row.min_in;
        MIN_IN_CURR_NAME = row.min_in_curr_name;
        opts = row.closed_rules
        for (var i in opts) {
            var valuta_inputs = '<input name="' + field.name + '[mavros][' + opts[i].id + '][currency]" class="_mavro_checkboxes" style="width: 90px;"/>';
            var multi = opts[i].multiple || 0;
            inputs += format(templ_i, field.name, opts[i].id, getTranslation(opts[i].value), valuta_inputs, ' style="display: none;" data-id_rule="' + opts[i].id + '"', '', multi);
        }
        var jj = 1;
        $.each(opts,
        function() {
            if (jj == 1) {
                BIG_SUMM_1_ID = this.id;
                BIG_SUMM_1_LIMIT = this.limit;
            }
            if (jj == 2) {
                BIG_SUMM_2_ID = this.id;
                BIG_SUMM_2_LIMIT = this.limit;
            }
            if (jj == 3) {
                BIG_SUMM_3_ID = this.id;
                BIG_SUMM_3_LIMIT = this.limit;
            }
            jj++;
        });
    }
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        $('#' + field.id).parent().find('._mavro_checkboxes').combobox({
            'required': true,
            'multiple': false,
            'editable': false,
            'value': (name_mavro != '' && name_mavro != 'null') ? selected_currency_id: 840,
            'valueField': 'id',
            'textField': 'value',
            'data': tm
        });
        var itm = $('#' + field.id);
        itm.data('type_input', row.type_input);
        bindEvents(itm, row.type_input, field.value);
    };
    $(this).data('callback', backs);
    if (typeof(selected_currency) == 'undefined') selected_currency = 810;
    return format(templ, field.id, field.name, inputs, field.value, field.prev_amount_in_curr, number_format(field.prev_amount_in_curr, 0, '.', ' ') + '&nbsp;' + selected_currency, field.rate_to_usd, field.id_country, field.value);
}
function fieldUserMavro(row) {
    templ = $('#_pattern_field_user_mavro').val();
    templ_i = $('#_pattern_field_user_mavro_item').val();
    var field = row;
    var opts = row.options ? row.options: [];
    var inputs = '';
    for (var i in opts) {
        inputs += format(templ_i, field.name, opts[i].id, getTranslation(opts[i].name), number_format(opts[i].value_curr, 2, ',', ' '), opts[i].currency_mavro, opts[i].value_curr, field.currency, opts[i].name, opts[i].currency_mavro, number_format(opts[i].value, 2, ',', ' '));
    }
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        currency_multy = parseFloat(field.multiple);
        var itm = $('#wizard_row_' + $(this).attr('id') + '_' + row.name);
        if (field.ba) {
            itm.find('._outmax').after('&nbsp;&nbsp;' + getTranslation('block_arrgs') + ': ' + field.ba);
        }
        itm.find('.translate').each(function() {
            $(this).text(getTranslation($(this).text(), {
                phone: field.options.phone
            }));
        });
        itm.find('._mavro_all').linkbutton({
            iconCls: 'icon-ok'
        }).click(function() {
            itm.find('._all').trigger('click');
        });
        itm.find('._all').click(function() {
            var $n = $(this).next();
            $n.val(number_format($n.attr('data-max'), 2, '.', ''));
            var s = 0;
            itm.find('._mavro_item').each(function() {
                s += parseFloat($(this).val());
            });
            total_out = s;
            if (total_out > data_out_max) {
                var to_i = parseFloat($n.val()) - (total_out - data_out_max);
                to_i = to_i > 0 ? to_i: 0;
                $n.val(to_i);
            }
            calcSums(itm);
            return false;
        }).linkbutton();
        bindMuEvents(itm);
    };
    $(this).data('callback', backs);
    MIN_OUT = number_format(field.min_out, 0, ',', ' ');
    MIN_OUT_CURR_NAME = field.min_out_curr_name;
    return format(templ, field.id, field.name, inputs, field.multiple, field.currency, field.rest_value, field.max_summ, number_format(field.max_summ, 2, ',', ' '));
}
function fieldCheckGroup(row) {
    templ = $('#_pattern_field_checkgroup').val();
    templ_i = $('#_pattern_field_check_item').val();
    var field = row;
    var opts = row.options ? row.options: [];
    var inputs = '';
    for (var i in opts) {
        inputs += format(templ_i, field.name + '[' + opts[i].id + ']', field.id + '_' + i, opts[i].id, getTranslation(opts[i].value), opts[i].checked ? ' checked="checked"': '');
    }
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        if (field.required) {
            $('#' + field.id).attr('required', 'required');
        }
    };
    $(this).data('callback', backs);
    return format(templ, field.id, inputs, field.style);
}
function fieldTextarea(row) {
    templ = $('#_pattern_field_textarea').val();
    var field = row;
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        $('#' + field.id).attr('name', field.name).val(field.value);
        $('#' + field.id).validatebox({
            required: row.required
        });
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldAllData(row) {
    var field = row;
    templ = '<div id="' + field.id + '"></div>';
    var opts = $(this).data('options') || {};
    var backs = $(this).data('callbacks');
    if (opts.paintAllData) {
        backs[backs.length] = function() {
            opts.paintAllData.call($('#' + field.id), field.all_data);
        };
    }
    $(this).data('callback', backs);
    return templ;
}
function fieldCheckbox(row) {
    templ = $('#_pattern_field_checkbox').val();
    var field = row;
    field['checked'] = row.value ? 'checked="checked"': '';
    field['required'] = field.required ? 'required="required"': '';
    return format(templ, field);
}
function doRequestSms(fname, mobile, type, back) {
    var _type = type || 'sms';
    var _back = back ||
    function(resp) {};
    var $win = $('<div class="panel window" style="display: block; width: 388px; left: 483px; top: 123px; z-index: 9012; position: absolute;"><div class="panel-header panel-header-noborder window-header" style="width: 388px;"><div class="panel-title">captcha</div><div class="panel-tool"></div></div><div style="padding: 10px; width: 366px; height: auto;" title="" class="panel-body panel-body-noborder window-body">' + '<table><tr><td>' + '	<img class="capcha" src="/c?' + (100000 * Math.random() + 10000) + '" style="border:1px solid lightslategrey;" /><br />' + '	<a class="recapcha" style="text-decoration:none;border-bottom:1px dashed #000;font-size:11px;cursor:pointer;">' + getTranslation('refresh_code') + '</a>' + '</td>' + '<td>' + '<label style="line-height:16px;margin:0 0 20px 0;">' + getTranslation('enter_captcha') + ':</label><br />' + '<input class="capcha" name="capcha" value="" type="text" style="width:100px;" />' + '</td></tr></table>' + '<div style="text-align: center;"><a class="_ok" >' + getTranslation('Ok') + '</a>&nbsp;<a class="_cancel" >' + getTranslation('Cancel') + '</a></div>' + '</div></div>');
    $win.appendTo('body');
    $('.recapcha', $win).click(function() {
        $('img.capcha', $win).attr('src', '/c?' + (100000 * Math.random() + 10000));
    });
    $('._ok', $win).linkbutton({
        iconCls: 'icon-ok'
    }).click(function() {
        var cc = $('input.capcha', $win).val();
        if (cc) {
            $.ajax({
                'url': '889.npl',
                data: {
                    'a': 'get_code',
                    'type': _type,
                    'cc': cc,
                    'fname': fname,
                    'mobile': mobile
                },
                success: function(data) {
                    if (handleState(data)) {
                        showAlert(data[23].message, 'info',
                        function() {
                            _back(data[23]);
                            $win.window('close');
                        });
                    } else {
                        showError(data[23])
                    }
                }
            });
        }
    });

    $('._cancel', $win).linkbutton({
        iconCls: 'icon-cancel'
    }).click(function() {
        $win.window('close');
    });
    $win.window({
        collapsible: false,
        title: 'captcha',
        minimizable: false,
        maximizable: false,
        closable: false,
        modal: true,
        width: 400,
        onClose: function() {
            $(this).window('destroy');
        }
    });
}
function doRequestEmail(fname, email, back) {
    $.ajax({
        'url': '890.npl',
        data: {
            'a': 'ver_email',
            'fname': fname,
            'email': email
        },
        success: function(data) {
            if (handleState(data)) {
                showAlert(getTranslation('to_your_email_{email}_has_send_code', {
                    email: data[23]
                }));
                back();
            } else {
                showError(data[23])
            }
        }
    });
}
function doRequestPhone(fname, phone, back) {
    $.ajax({
        'url': '890.npl',
        data: {
            'a': 'ver_phone',
            'fname': fname,
            'phone': phone
        },
        success: function(data) {
            if (handleState(data)) {
                if (typeof(data.voiced) != 'undefined' && parseInt(data.voiced, 10)) {
                    showAlert(getTranslation('to_your_phone_{phone}_has_send_voice', {
                        phone: data[23]
                    }));
                } else {
                    showAlert(getTranslation('to_your_phone_{phone}_has_send_code', {
                        phone: data[23]
                    }));
                }
                back();
            } else {
                showError(data[23])
            }
        }
    });
}
function fieldSms(row) {
    templ = $('#_pattern_field_sms').val();
    var field = row;
    var opts = row.options ? row.options: [];
    var backs = $(this).data('callbacks');
    if (parseInt(opts.code_sended, 10) != 0) {
        field.code_num = getTranslation('enter_code_{num}', {
            num: opts.code_info.num
        }) + '&nbsp;';
    } else {
        field.code_num = '';
    }
    backs[backs.length] = function() {
        if (parseInt(opts.code_sended, 10) == 0 && parseInt(opts.has_ga, 10) == 0) {
            $('.no_code', '#' + field.id).show();
        } else {
            $('.yes_code', '#' + field.id).show();
        }
        $('#' + field.id).find('.translate').each(function() {
            $(this).text(getTranslation($(this).text(), {
                phone: field.options.phone
            }));
        });
        $('#' + field.id).find('._request_sms').click(function() {
            doRequestSms(field.name, field.options.phone, 'sms',
            function(resp) {
                $('.no_code', '#' + field.id).hide();
                $('.yes_code', '#' + field.id).show();
                $('span.code_num', '#' + field.id).html(getTranslation('enter_code_{num}', {
                    num: resp.code_info.num
                }) + '&nbsp;');
            });
            return false;
        }).linkbutton();
        $('#' + field.id).find('._request_voice').click(function() {
            doRequestSms(field.name, field.options.phone, 'voice',
            function(resp) {
                $('span.code_num', '#' + field.id).html(getTranslation('enter_voice_code') + '&nbsp;');
            });
            return false;
        }).linkbutton();
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldPhoneInstall(row) {
    templ = $('#_pattern_field_phone_install').val();
    var field = row;
    var opts = row.options ? row.options: [];
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        $('.translate', '#' + field.id).each(function() {
            $(this).text(getTranslation($(this).text()));
        });
        $('a', '#' + field.id).click(function() {
            if ($('[name="' + row.name + '"]', '#' + field.id).val()) {
                doRequestPhone(row.name, $('[name="' + row.name + '"]', '#' + field.id).val(),
                function() {
                    $('.translate', '#' + field.id).show();
                    $('.code', '#' + field.id).show();
                });
            }
        }).linkbutton();
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function checkTimeCode(name, parent, code) {
    var code = code || '';
    $.ajax({
        'url': '890.npl',
        data: {
            a: 'time_check_email',
            email: $('[name="' + name + '"]', parent).val(),
            code: code
        },
        success: function(data) {
            if (handleState(data)) {
                $('.code', parent).html(getTranslation('confirmed'));
                $(window).unbind('focus');
            }
        }
    });
}
function fieldEmailInstall(row) {
    templ = $('#_pattern_field_email_install').val();
    var field = row;
    var opts = row.options ? row.options: [];
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        var input = $('[name="' + row.name + '"]', '#' + field.id);
        input.validatebox({
            validType: 'email',
            required: 'true'
        });
        $('.translate', '#' + field.id).each(function() {
            $(this).text(getTranslation($(this).text()));
        });
        $('a', '#' + field.id).click(function() {
            if (input.validatebox('isValid')) {
                doRequestEmail(row.name, $('[name="' + row.name + '"]', '#' + field.id).val(),
                function() {
                    $('.translate', '#' + field.id).show();
                    $('.code', '#' + field.id).show();
                    $('[name="' + row.name + '"]', '#' + field.id).attr('disabled', 'disabled');
                    $('._request_email', '#' + field.id).linkbutton('disable');
                    $(window).focus(function() {
                        checkTimeCode(row.name, '#' + field.id);
                    });
                    $('.code input', '#' + field.id).change(function() {
                        checkTimeCode(row.name, '#' + field.id, $(this).val());
                    });
                });
            }
        }).linkbutton();
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function fieldPassword(row) {
    templ = $('#_pattern_field_password').val();
    var field = row;
    var opts = row.options ? row.options: [];
    var backs = $(this).data('callbacks');
    backs[backs.length] = function() {
        $('.translate', '#' + field.id).each(function() {
            $(this).text(getTranslation($(this).text()));
        });
        $('input', '#' + field.id).change(function() {
            var i1 = $('input', '#' + field.id)[0];
            var i2 = $('input', '#' + field.id)[1];
            if (($(i1).val() || $(i2).val()) && $(i2).val() != $(i1).val()) {
                $(i1).addClass('wrong');
                $(i2).addClass('wrong');
            } else {
                $(i1).removeClass('wrong');
                $(i2).removeClass('wrong');
            }
        });
    };
    $(this).data('callback', backs);
    return format(templ, field);
}
function buildField(row) {
    row.id = 'wizard_field_' + $(this).attr('id') + '_' + row.name;
    row.title = getTranslation(row.title);
    row.required = parseInt(row.required) ? true: false;
    row.style = typeof(row.style) != 'undefined' ? row.style: '';
    switch (row.type) {
    case 'checkbox':
        return fieldCheckbox.call(this, row);
        break;
    case 'combo':
        return fieldCombo.call(this, row);
        break;
    case 'multi_combobox':
        return fieldMultiCombo.call(this, row);
        break;
    case 'date':
        return fieldDate.call(this, row);
        break;
    case 'textarea':
        return fieldTextarea.call(this, row);
        break;
    case 'file':
        return fieldFile.call(this, row);
        break;
    case 'info':
        return fieldInfo.call(this, row);
        break;
    case 'radio':
        return fieldRadio.call(this, row);
        break;
    case 'checkgroup':
        return fieldCheckGroup.call(this, row);
        break;
    case 'mavro_amounts':
        return fieldMavroAmounts.call(this, row);
        break;
    case 'user_mavro':
        return fieldUserMavro.call(this, row);
        break;
    case 'captcha':
        return fieldCaptcha.call(this, row);
        break;
    case 'sms':
        return fieldSms.call(this, row);
        break;
    case 'requisite':
        return fieldRequisite.call(this, row);
        break;
    case 'label':
        return fieldLabel.call(this, row);
        break;
    case 'phone_install':
        return fieldPhoneInstall.call(this, row);
        break;
    case 'email_install':
        return fieldEmailInstall.call(this, row);
        break;
    case 'passwd':
        return fieldPassword.call(this, row);
        break;
    case 'all_data':
        return fieldAllData.call(this, row);
        break;
    case 'text':
    default:
        return fieldDefault.call(this, row);
    }
}
function buildRow(row) {
    rows_templ = $('#_pattern_wizard_rows').val();
    var field = buildField.call(this, row);
    var title = getTranslation(row.title);
    return ['wizard_row_' + $(this).attr('id') + '_' + row.name, title, field, getTranslation(row.descr), row.type];
}
function doCancel() {
    var options = $(this).data('options');
    if (options.cancel) {
        options.cancel.call(this);
    }
    $(this).wizard('remove');
    destroyWizards();
}
function doOk(button) {
    var options = $(this).data('options') || {};
    var dt = $(this).wizard('getData');
    if (dt._error) {
        $.messager.alert(getTranslation('Warning'), getTranslation(dt._error_messages[0]), 'error',
        function() {
            dt._error_focuses[0].focus();
        });
        return false;
    }
    var el = this;
    if (dt) {
        if (!options.advCheck) {
            options.advCheck = function(dt, f) {
                f(dt);
            };
        }
        options.advCheck(dt,
        function(dt) {
            loadingShow();
			
			var data={"8":0,"200":1,"205":"out_request_11"};
			
                    loadingHide();
                    if (handleState(data)) {
                        var status = data['200'];
                        if (status == '0') {
                            var message = getTranslation(data['204']) || false;
                            if (message) showAlert(message, 'info',
                            function() {
                                $(el).wizard('remove');
                                if (options.end) {
                                    options.end.call(el);
                                }
                            });
                            else {
                                $(el).wizard('remove');
                                if (options.end) {
                                    options.end.call(el);
                                }
                            }
                        } else if (data['200'] == '1') {
                            if (options.nextStep) options.nextStep.call(el, data['205']);
                            $(el).wizard(data['205'], options);
                        } else if (data['200'] == '2') {
                            var field = data['202'] || false;
                            var message = data['203'] ? getTranslation(data['203'], {
                                field: $('[name="' + field + '"]').parent().prev().text()
                            }) : getTranslation('Field filled invalid', {
                                field: $('[name="' + field + '"]').parent().prev().text()
                            });
                            showAlert(message, 'error',
                            function() {
                                if (field) {
                                    $('[name="' + field + '"]').focus();
                                }
                            });
                        } else if (data['200'] == '3') {
                            var message = data['203'] || 'Save error';
                            showAlert(getTranslation(message), 'error',
                            function() {
                                $(el).wizard('remove');
                                if (options.end) {
                                    options.end.call(el);
                                }
                            });
                        } else if (data['200'] == '4') {
                            $(el).wizard('remove');
                            if (options.end) {
                                options.end.call(el);
                            }
                        }
                    } else {
                        showAlert(getTranslation('Unknown error'), 'error',
                        function() {
                            $(el).wizard('remove');
                            if (options.end) {
                                options.end.call(el);
                            }
                        });
                    }
                
			
           
        });
    }
    return false;
}
function doBack() {
    var options = $(this).data('options') || {}
    var el = this;
	var data={"text":"{0}<br class=\"clear\" \/>{1}","rows":[{"title":"out_request_select_account","type":"radio","name":"typeof_account","descr":"out_request_select_account_comment","style":"","value":"adeposit_choose_zero_exist_account","required":0,"regexp":"","regexp_keys":"","maxlength":"0","show":true,"options":[{"id":"adeposit_choose_zero_exist_account","value":"adeposit_choose_zero_exist_account"},{"id":"adeposit_attach_new_account","value":"adeposit_attach_new_account"}]}],"b1":"","b2":"Next","b3":"Cancel","i":"d93a476967","i18":0,"w":"out_request_1"};
	 if (handleState(data)) {
                if (options.nextStep) options.nextStep.call(el, data['205']);
                $(el).wizard(data['205'], options);
            }
   
    return false;
}
function enableButtons() {
    $(this).find('.wizard_actions [iconCls]').each(function() {
        $(this).linkbutton('enable');
    });
}
function disableButtons() {
    $(this).find('.wizard_actions [iconCls]').each(function() {
        $(this).linkbutton('disable');
    });
}
function createWizard(defs) {
    if (defs['8'] > 0) {
        var mess = getTranslation(defs['23']);
        if (mess) $.messager.alert('Permission ERROR!', mess, 'error');
        return;
    }
    var opts = $(this).data('options') || {};
    el = this;
    $(el).data('callbacks', []);
    main_templ = $('#_pattern_wizard_main').val();
    form_templ = $('#_pattern_wizard_form').val();
    rows_templ = $('#_pattern_wizard_rows').val();
    row_templ = $('#_pattern_wizard_row').val();
    row_templ_adv = $('#_pattern_wizard_row_adv').val();
    act_templ = $('#_pattern_wizard_actions').val();
    var rows = '';
    for (var i in defs.rows) {
        if (defs.rows[i].required && defs.rows[i].required != 'f') {
            defs.rows[i].required = 1;
        } else {
            defs.rows[i].required = 0;
        }
        var show_field = defs.rows[i].show;
        if (show_field) {
            var row_data = buildRow.call(el, defs.rows[i]);
            if (defs.rows[i]['type'] == 'requisite') {
                rows += format(row_templ_adv, row_data);
            } else {
                rows += format(row_templ, row_data);
            }
        }
    }
    var rows_html = format(rows_templ, 'wizard_rows_' + $(el).attr('id'), rows);
    var form = format(form_templ, 'wizard_form_' + $(el).attr('id'), rows_html, defs.i, defs.w, defs.i18, (selectedUserId > 0) ? selectedUserId: user_perms.id);
    var b1 = defs.b1 ? '<a iconcls="icon-back" class="easyui-linkbutton l-btn" href="#">' + getTranslation(defs.b1) + '</a>': '';
    var b2 = defs.b2 ? '<a iconcls="icon-ok" class="easyui-linkbutton l-btn" href="#">' + getTranslation(defs.b2) + '</a>': '';
    var b3 = defs.b3 ? '<a iconcls="icon-cancel" class="easyui-linkbutton l-btn" href="#">' + getTranslation(defs.b3) + '</a>': '';
    var actions = format(act_templ, b1, b2, b3);
    $(el).html(format(main_templ, {
        'id': defs.id ? defs.id: 'wizard_' + defs.wizard_form,
        'content': format(getTranslation(defs.text), form, actions)
    }));
    $(el).find('.easyui-linkbutton').linkbutton();
	
	/*20160217 修改*/
	
   /* if (b3) {
        $(el).find('[iconcls="icon-cancel"]').die().live('click',
        function() {
            doCancel.call(el);
            return false;
        });
    }*/
    if (b2) {
        $(el).find('[iconcls="icon-ok"]').die().live('click',
        function() {
			
            /*if (!$(this).linkbutton('options').disabled) {
                enableButtons.call(el);
                doOk.call(el, this);
            }
            return false;*/
        });
    }
    if (b1) {
        $(el).find('[iconcls="icon-back"]').die().live('click',
        function() {
            doBack.call(el);
            return false;
        });
    }
    var backs = $(el).data('callbacks');
    $('.translate', $(el)).each(function() {
        $(this).html(getTranslation($(this).html()));
    });
    for (i in backs) {
        backs[i].call(el);
    }
    if (opts.load) {
        opts.load.call(el);
    }
    $(el).find(".wizard_row_descr .hintlink").each(function() {

        $(this).attr('title', $(this).next(".hintbody").html()).qtip({
            position: {
			    my: 'top right',  // Position my top left...
                at: 'bottom left', // at the bottom right of...              
            },			
        });
    });
    $(el).ajaxStart(function() {
        loadingShow();
    });
    $(el).ajaxStop(function() {
        loadingHide();
    });
}
function getWizardData() {
    var dt = {};
    var i = 0;
    var opts = $(this).data('options') || {};
    if (opts.onValidate) {
        opts.onValidate.call(this);
    }
    var custom_message = '';
    dt._error_fields = [];
    dt._error_messages = [];
    dt._error_focuses = [];
    $(this).find('[name], .radio_group, .field_mavro_amounts, .field_file, .validatebox-text, .chekgroup_items').each(function() {
        var field_error = false;
        var error_focus = [];
        var cm = '';
        if ($(this).attr('type') == 'checkbox') {
            if ($(this).attr('required') == 'required') {
                if ($(this).attr('checked') != 'checked') {
                    field_error = true;
                    error_focus = $(this);
                    cm = getTranslation('you_must_accept_terms');
                }
            }
        }
        if (this.requisite) {
            var err = !this.requisite.validate();
            if (err && this.requisite.errors[0]) {
                field_error = true;
                error_focus = $(this);
                cm = getTranslation(this.requisite.errors[0].message);
            }
        }
        if ($(this).data('validatebox') && !$(this).validatebox('isValid')) {
            field_error = true;
            error_focus = $(this);
        }
        if ($(this).hasClass('wizard-invalid')) {
            field_error = true;
            error_focus = $(this);
        }
        if ($(this).hasClass('field_file') && $(this).attr('required')) {
            $c = $(this).find('ul.qq-upload-list li.qq-upload-success').length;
            if (!$c) {
                field_error = true;
                error_focus = $(this);
                cm = getTranslation('Please select file');
            }
        }
        if ($(this).hasClass('field_mavro_amounts')) {
            var $t = $(this).find('._total');
            var type = parseInt($t.data('type_input'));
            var ttd = (type == 1) ? parseInt($t.data('real_value')) : parseFloat($t.val());
            t = (type == 1 || type == 2) ? ttd: to_dist;
            var s = 0;
            $(this).find('._mavro_item').each(function() {
                s += parseFloat($(this).val());
            });
            if (ttd == 0 || !$t.attr('disabled')) {
                field_error = true;
                error_focus = $t;
            }
            if (s != t) {
                field_error = true;
                error_focus = $t;
                cm = getTranslation('Please distribute your moneys between types');
            }
        }
        if (($(this).hasClass('radio_group') || $(this).hasClass('chekgroup_items')) && $(this).attr('required')) {
            var chk = false;
            $(this).find('[name]').each(function() {
                chk = chk || this.checked;
            });
            if (!chk) {
                field_error = true;
                error_focus = $(this).find('[name]').eq(0);
                cm = getTranslation('Please select one of variants');
            }
        }
        if (field_error) {
            dt._error = 1;
            dt._error_fields.push($(this).attr('id'));
            dt._error_focuses.push(error_focus);
            cm = cm ? cm: $(this).data('_error_message');
            dt._error_messages.push(cm ? cm: getTranslation('input_valid_data'));
        }
        if ($(this).attr('type') == 'checkbox') {
            dt[$(this).attr('name')] = $(this).attr('checked') ? 1 : 0;
        } else if ($(this).attr('type') == 'radio') {
            if (this.checked) {
                dt[$(this).attr('name')] = $(this).val();
            }
        } else if ($(this).hasClass('label')) {
            dt[$(this).attr('name')] = $(this).html();
        } else if ($(this).parent().hasClass('datebox')) {
            var val = $(this).val();
            var p = val.split('.');
            val = p[2] + '-' + p[1] + '-' + p[0];
            dt[$(this).attr('name')] = val;
        } else if (parseInt($(this).data('type_input')) == 1 || parseInt($(this).data('type_input')) == 1) {
            dt[$(this).attr('name')] = $(this).data('real_value');
        } else if ($(this).parents('.wizard_row_field').hasClass('field_multi_combobox')) {
            if (typeof dt[$(this).attr('name')] == 'string' || typeof dt[$(this).attr('name')] == 'undefined') {
                dt[$(this).attr('name')] = [];
            }
            dt[$(this).attr('name')].push($(this).val());
        } else if (this.requisite) {
            dt[$(this).attr('name')] = $(this).requisite('getData');
        } else {
            dt[$(this).attr('name')] = $(this).val();
        }
    });
    return dt;
}
$.fn.wizard = function(defs) {
    var el = $(this).get(0);
    if (el) {
        var options = {};
        if (arguments.length > 1) {
            if (typeof(arguments[1]) == 'object') {
                options = arguments[1];
                $(el).data('options', options);
            }
        }
        if (typeof(defs) == 'object') {
            createWizard.call(el, defs);
        } else {
            if (typeof(defs) == 'string') {
                if (defs == 'getData') {
                    return getWizardData.call(el);
                } else if (defs == 'remove') {
                    $(el).html('');
                } else {
                    loadingShow();
                    var i18 = options.i18 ? options.i18: 0;
                    var i23 = options.i23 ? options.i23: 0;
					var data={"text":"{0}<br class=\"clear\" \/>{1}","rows":[{"title":"out_request_select_account","type":"radio","name":"typeof_account","descr":"out_request_select_account_comment","style":"","value":"adeposit_choose_zero_exist_account","required":0,"regexp":"","regexp_keys":"","maxlength":"0","show":true,"options":[{"id":"adeposit_choose_zero_exist_account","value":"adeposit_choose_zero_exist_account"},{"id":"adeposit_attach_new_account","value":"adeposit_attach_new_account"}]}],"b1":"","b2":"Next","b3":"Cancel","i":"d93a476967","i18":0,"w":"out_request_1"};
					
                            loadingHide();
                            createWizard.call(el, $.extend(data, {
                                wizard_form: defs
                            }));                      					
                }
            }
        }
    }
    return this;
};
function destroyWizards(callback) {
    loadingShow();
     var data={"8":0};
     loadingHide();
            if (callback) {
                callback();
            }       
}